import os

from PyQt5.Qt import *
import pyqtgraph as pg
import cgitb
from UI.settingdockwidget_v2 import Ui_settingDockWidget
from windows.disableeditor import DisableEditor
from ExtendWidgets import E_LineEdit
cgitb.enable(format='text')
pg.setConfigOptions(antialias=True)
from windows.selectWin import SelectWindow
import sys
import struct
import numpy as np
import scipy
import scipy.signal
from scipy.fftpack import fftshift
from scipy.signal import stft


class FileSelectWidget(QWidget):
    def __init__(self, parent=None, filter = None):
        super(FileSelectWidget, self).__init__(parent)
        self.filter = filter if filter is not None else "Bin Files(*.bin)"
        self.horizontalLayout = QHBoxLayout(self)
        self.horizontalLayout.setSpacing(1)
        self.horizontalLayout.setContentsMargins(0, 0, 0, 0)

        self.gloabal_path = E_LineEdit(self)
        self.gloabal_path.setReadOnly(True)
        self.pushButton = QPushButton(self)
        self.pushButton.setText("...")
        self.pushButton.setStyleSheet("min-width: 25px")
        self.pushButton.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        self.horizontalLayout.addWidget(self.gloabal_path)
        self.horizontalLayout.addWidget(self.pushButton)
        self.pushButton.clicked.connect(self.getPath)
        self.gloabal_path.cursorPositionChanged.connect(
            lambda: self.gloabal_path.setCursorPosition(0))

    def getPath(self):
        path, _ = QFileDialog.getOpenFileName(self, "训练数据选取", ".", self.filter)
        if path == "":
            return
        self.gloabal_path.setText(os.path.abspath(path))
        self.gloabal_path.setCursorPosition(0)




class DirSelectWidget(QWidget):

    def __init__(self, parent=None):
        super(DirSelectWidget, self).__init__(parent)

        self.horizontalLayout = QHBoxLayout(self)
        self.horizontalLayout.setSpacing(1)
        self.horizontalLayout.setContentsMargins(0, 0, 0, 0)

        self.gloabal_path = E_LineEdit(self)
        self.gloabal_path.setReadOnly(True)
        self.gloabal_path.setPlaceholderText("C:\Anomaly Detection")
        self.pushButton = QPushButton(self)
        self.pushButton.setText("...")
        self.pushButton.setStyleSheet("min-width: 25px")
        self.pushButton.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        # self.pushButton.setStyleSheet("max-width: 25px")
        self.horizontalLayout.addWidget(self.gloabal_path)
        self.horizontalLayout.addWidget(self.pushButton)
        self.pushButton.clicked.connect(self.getPath)
        self.gloabal_path.cursorPositionChanged.connect(
            lambda: self.gloabal_path.setCursorPosition(0))

    def getPath(self):
        path = QFileDialog.getExistingDirectory(self, "路径选取", ".", QFileDialog.ShowDirsOnly)
        if path == "":
            return
        self.gloabal_path.setText(os.path.abspath(path))
        self.gloabal_path.setCursorPosition(0)


class MinMaxWidget(QWidget):
    def __init__(self, parent=None):
        super(MinMaxWidget, self).__init__(parent)

        self.horizontalLayout = QHBoxLayout(self)
        self.horizontalLayout.setSpacing(1)
        self.horizontalLayout.setContentsMargins(0, 0, 0, 0)
        self.freq_double_spin_box = QDoubleSpinBox(self)
        self.freq_double_spin_box.setMinimum(0)
        self.freq_double_spin_box.setMaximum(1000000000)
        self.pushButton = QPushButton(self)
        self.pushButton.setText("...")
        self.pushButton.setStyleSheet("min-width: 25px")
        self.pushButton.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        self.horizontalLayout.addWidget(self.freq_double_spin_box)
        self.horizontalLayout.addWidget(self.pushButton)




class SettingDockWidget(Ui_settingDockWidget, QDockWidget):

    def __init__(self, parent=None):
        super(SettingDockWidget, self).__init__(parent)
        self.setupUi(self)
        self.created = False  # 频段选择窗口是否创建


        self.treeWidgetSetting.setItemDelegateForColumn(0, DisableEditor(self.treeWidgetSetting))
        self.setWindowTitle("参数配置")
        self.path_setting: QTreeWidgetItem = self.treeWidgetSetting.findItems("路径设置", Qt.MatchExactly)[0]
        self.train_setting: QTreeWidgetItem = self.treeWidgetSetting.findItems("训练设置", Qt.MatchExactly)[0]
        self.model_manage: QTreeWidgetItem = self.treeWidgetSetting.findItems("模型管理", Qt.MatchExactly)[0]

        # self.trainModelMethod:QTreeWidgetItem = self.treeWidgetSetting.findItems("模型训练方法", Qt.MatchExactly)[0]

        self.fft_setting: QTreeWidgetItem = self.treeWidgetSetting.findItems("STFT相关设置", Qt.MatchExactly)[0]
        # self.comboBox_method = QComboBox(self)
        # self.comboBox_method.addItems(['单频段单模型', '多频段单模型'])
        # self.treeWidgetSetting.setItemWidget(self.trainModelMethod, 1, self.comboBox_method)


        self.path_widget = DirSelectWidget(self) # 全局保存路径
        self.treeWidgetSetting.setItemWidget(self.path_setting.child(0), 1, self.path_widget)


        self.picture_save_linedit = E_LineEdit(self)
        self.picture_save_linedit.setPlaceholderText("Train Pictures")
        self.treeWidgetSetting.setItemWidget(self.path_setting.child(1), 1, self.picture_save_linedit)

        self.spinbox_nperseg = QSpinBox(self)
        self.spinbox_nperseg.setMinimum(0)
        self.spinbox_nperseg.setMaximum(100000000)
        self.treeWidgetSetting.setItemWidget(self.fft_setting.child(0), 1, self.spinbox_nperseg)

        self.spinbox_noverlap = QSpinBox(self)
        self.spinbox_noverlap.setMinimum(0)
        self.spinbox_noverlap.setMaximum(100000000)
        self.treeWidgetSetting.setItemWidget(self.fft_setting.child(1), 1, self.spinbox_noverlap)

        self.spinbox_nfft = QSpinBox(self)
        self.spinbox_nfft.setMinimum(0)
        self.spinbox_nfft.setMaximum(100000000)
        self.treeWidgetSetting.setItemWidget(self.fft_setting.child(2), 1, self.spinbox_nfft)

        self.spinbox_time_segment = QSpinBox(self)
        self.spinbox_time_segment.setMinimum(0)
        self.spinbox_time_segment.setMaximum(100000000)
        self.treeWidgetSetting.setItemWidget(self.fft_setting.child(3), 1, self.spinbox_time_segment)

        self.double_spinbox_sample_freq = QDoubleSpinBox(self)
        self.double_spinbox_sample_freq.setMinimum(0)
        self.double_spinbox_sample_freq.setMaximum(10000000)
        self.treeWidgetSetting.setItemWidget(self.fft_setting.child(4), 1, self.double_spinbox_sample_freq)

        self.double_spinbox_center_freq = QDoubleSpinBox(self)
        self.double_spinbox_center_freq.setMinimum(0)
        self.double_spinbox_center_freq.setMaximum(10000000)
        self.treeWidgetSetting.setItemWidget(self.fft_setting.child(5), 1, self.double_spinbox_center_freq)
        self.double_spinbox_center_freq.editingFinished.connect(self.setLimits)
        self.double_spinbox_sample_freq.editingFinished.connect(self.setLimits)
        # self.min_freq_double_spin_box = QDoubleSpinBox(self)
        # self.min_freq_double_spin_box.setMinimum(0)
        # # self.min_freq_double_spin_box.setStyleSheet("border: 0px;")
        # self.treeWidgetSetting.setItemWidget(self.train_setting.child(0), 1, self.min_freq_double_spin_box)
        self.train_data_path_widget = FileSelectWidget(self, filter="Bin Files(*.bin)")
        self.treeWidgetSetting.setItemWidget(self.train_setting.child(0), 1, self.train_data_path_widget)


        self.min_freq_setting = MinMaxWidget(self)
        self.treeWidgetSetting.setItemWidget(self.train_setting.child(1), 1, self.min_freq_setting)

        self.max_freq_setting = MinMaxWidget(self)
        self.treeWidgetSetting.setItemWidget(self.train_setting.child(2), 1, self.max_freq_setting)



        self.test()


    def setLimits(self):
        F0 =self.double_spinbox_center_freq.value()
        Fs = self.double_spinbox_sample_freq.value()
        self.min_freq_setting.freq_double_spin_box.setMinimum(F0 - Fs / 2)
        self.max_freq_setting.freq_double_spin_box.setMinimum(F0 - Fs / 2)

        self.min_freq_setting.freq_double_spin_box.setMaximum(F0 + Fs / 2)
        self.max_freq_setting.freq_double_spin_box.setMaximum(F0 + Fs / 2)

    def test(self):
        self.train_data_path_widget.gloabal_path.setText(r"D:\异常检测项目最新版\DATA\DATA5yi.bin")
        self.spinbox_nperseg.setValue(2048)
        self.spinbox_nfft.setValue(2048)
        self.spinbox_time_segment.setValue(10)
        self.double_spinbox_center_freq.setValue(250)
        self.double_spinbox_sample_freq.setValue(100)
        self.spinbox_noverlap.setValue(1024)

    @staticmethod
    def getReadLength(time_col, window_length, noverlap):
        return (time_col - 3) * (window_length - noverlap) + window_length



if __name__ == '__main__':
    app = QApplication(sys.argv)
    win = SettingDockWidget()
    win.show()

    sys.exit(app.exec_())
